package com.project.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.model.MemberModel;
import com.project.service.MemberService;
import com.project.utils.HttpRequestUtils;

@Controller
@RequestMapping(value = "/sms")
public class SendSMSController {
	private static Logger logger = LoggerFactory.getLogger(SendSMSController.class);
	
	@Autowired
	private MemberService memberService;
	
	private final static String send_sms_url = "http://sdk4http.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=CDKEY&password=PASSWORD&phone=PHONE&message=MESSAGE";
	private final static int session_time = 5*60;
	
	private String cdkey = "3SDK-EMY-0130-JITST";
	private String password = "198118";
	
	@RequestMapping("register")
	public @ResponseBody Map<String, String> sms_register(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String phone = request.getParameter("phone");
		
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[2-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "-1");
				map.put("msg", "手机号码有误，请重填");
			}
		}
		
		List<MemberModel> imList = memberService.getMemberModelByPhone(phone);
		if (imList.size() == 0) {
			HttpSession session = request.getSession();
			String code = sendSMS(phone);
			if (!"".equals(code)) {
				session.setMaxInactiveInterval(session_time);
				session.setAttribute("sms_code", code+","+phone);
				map.put("code", "0");
				map.put("msg", "短信已发送");
			} else {
				map.put("code", "-1");
				map.put("msg", "短信发送失败");
			}
		} else {
			//会员存在，提示
			map.put("code", "-1");
			map.put("msg", "手机号码[" + phone + "]已被注册");
		}
		return map;
	}
	
	
	@RequestMapping("change_password")
	public @ResponseBody Map<String, String> sms_change_password(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String phone = request.getParameter("phone");
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[2-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "-1");
				map.put("msg", "手机号码有误，请重填");
			}
		}
		List<MemberModel> imList = memberService.getMemberModelByPhone(phone);
		if (imList.size() > 0) {
			HttpSession session = request.getSession();
			String code = sendSMS(phone);
			if (!"".equals(code)) {
				session.setMaxInactiveInterval(session_time);
				session.setAttribute("sms_code", code+","+phone);
				map.put("code", "0");
				map.put("msg", "短信已发送");
			} else {
				map.put("code", "-1");
				map.put("msg", "短信发送失败");
			}
		} else {
			//会员存在，提示
			map.put("code", "-1");
			map.put("msg", "手机号码[" + phone + "]不存在");
		}
		return map;
	}
	
	private String sendSMS(String phone){
		String code = getFixLenthString(6);
		String message = "【八号便利店】您本次在寻宝请求的验证码是："+code+"，有效实时间为5分钟";
		String requestUrl = send_sms_url.replace("CDKEY", cdkey).replace("PASSWORD", password).replace("PHONE", phone).replace("MESSAGE", message);
		// JSONObject jsonObject = HttpRequestUtils.httpGet(requestUrl);
		HttpEntity httpEntity = HttpRequestUtils.httpEntityGet(requestUrl);
		try {
			String strResult = inputStreamToString(httpEntity.getContent());
			// ".*<error>0</error>.*"
			if (!strResult.matches(".*<error>0</error>.*")) {
				code = "";
			}
		} catch (ParseException | IOException e) {
			code = "";
			logger.info(">>> " + e.getMessage());
		}
		return code;
	}
	
	private String getFixLenthString(int strLength) {
	    Random rm = new Random();
	    // 获得随机数  
	    double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);
	    // 返回固定的长度的随机数
	    return fixLenthString.substring(1, strLength + 1);
	}
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[2-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	
	private String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
        	logger.info(">>> " + e.getMessage());
            // Log.e(TAG, e.getLocalizedMessage(), e);
        }
        // Return full string
        return total.toString();
    }
	
}